import { createRouter, createWebHistory } from 'vue-router';
import MainLayout from '@/views/layouts/MainLayout.vue';
import HomeView from '../views/HomeView.vue';
import DashboardIndex from '../views/dashboard/DashboardIndex.vue';
import PlantList from '../views/plants/PlantList.vue';
import PlantEdit from '../views/plants/PlantEdit.vue';
import AdoptionList from '../views/adoption/AdoptionList.vue';
import UserList from '../views/users/UserList.vue';
import NotFound from '../views/NotFound.vue';
import LoginView from '../views/LoginView.vue';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginView
  },
  {
    path: '/',
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      { path: '', name: 'home', component: HomeView, meta: { title: '首页' } },
      { path: 'dashboard', name: 'dashboard', component: DashboardIndex, meta: { title: '仪表盘' } },
      { path: 'plants', name: 'plants', component: PlantList, meta: { title: '植物管理' } },
      { path: 'plants/new', name: 'plant-new', component: PlantEdit, meta: { title: '新增植物' } },
      { path: 'plants/edit/:id', name: 'plant-edit', component: PlantEdit, meta: { title: '编辑植物' } },
      { path: 'adoptions', name: 'adoptions', component: AdoptionList, meta: { title: '领养管理' } },
      { path: 'users', name: 'users', component: UserList, meta: { title: '用户管理' } }
    ]
  },
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn');
  if (to.matched.some(record => record.meta.requiresAuth) && !isLoggedIn) {
    next('/login');
  } else {
    next();
  }
});

export default router;
